/**
 * 权限
 */
import fullRoutes from '@/router/routes'
import store from '../../store'
import { filterRoutes } from '../../utils/router'
import path from 'path'
// let routes = []
export default {
  namespaced: true, // 启用命名空间，使用的时候是 命名空间/mutation 命名空间/action
  state: {
    routes: [],
    menus: []
  },
  getters: {
  },
  /**
   * store 中的状态的唯一方法
   * 通过store.commit()方法触发，来改变状态值
   */
  mutations: {
    'SET_ROUTES' (state, routes) {
      state.routes.splice(0, state.routes.length, ...routes)
    },
    'SET_MENUS' (state, menus) {
      state.menus.splice(0, state.menus.length, ...menus)
    }
  },
  /**
   * 通过store.dispatch()方法来触发
   */
  actions: {
    'GenerateRoutes' ({ commit, dispatch }) {
      console.log('store.state.user.id', JSON.stringify(store.state.user))
      return filterRoutes(fullRoutes, store.state.user.id).then(routes => {
        commit('SET_ROUTES', routes)
        dispatch('GenerateMenus', routes)
        return Promise.resolve(routes)
      })
    },
    'GenerateMenus' ({ commit }, routes) {
      const menus = filterMenus(routes)
      console.log(menus)
      commit('SET_MENUS', menus)
      commit('app/UPDATE_SIDE_BAR_MENUS', menus, { root: true })
    }
  }
}

function filterMenus (items, parent) {
  const result = []
  items.forEach(item => {
    const level = parent ? [].concat(parent.meta.level) : []
    const current = Object.assign({}, item)
    if (item.meta) {
      current.title = item.meta.title
    }
    current.meta = current.meta || {}
    current.meta.level = level
    level.push(current)
    current.fullPath = path.resolve(
      ...(level.slice(1).map(value => value.path))
    )
    if (item.children) {
      // 有子节点
      if (!item.hidden) {
        // 不隐藏时
        const children = filterMenus(item.children, current)
        if (children.length || item.alwayShow) {
          // 存在子节点 或 强制显示
          current.children = children
          result.push(current)
        }
      }
    } else {
      // 没有子节点
      if (!item.hidden) {
        result.push(current)
      }
    }
  })
  return result
}
